import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Form, Input, List, Card, Grid, Toast, ErrorBlock } from "antd-mobile";
import { BottomBtn } from "@components";
import { REQUIRED_RULE, BARCODE_PARSER } from "@common/constants";
import {
  createAction,
  subscribeScanEvent,
  unSubscribeScanEvent,
  callNativeApi,
} from "@common/utils";
import { SET_SCAN_DATA } from "@store/global-state/action-types";
import { SAGA_UNPACK_SAVE } from "@store/unpack/saga-types";

const UnpackOpsObj = {
  subscribe: null,
  unsubscribe: null,
  setFields: null,
  handleScan: null,
};

const Ops = () => {
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const [items, setItems] = useState([]);

  const Description = ({ title, record }) => (
    <Card title={title}>
      <Grid columns={2} gap={12}>
        <Grid.Item>物料条码</Grid.Item>
        <Grid.Item>{record.itemBarcode}</Grid.Item>
        <Grid.Item>物料编码</Grid.Item>
        <Grid.Item>{record.itemCode}</Grid.Item>
        <Grid.Item>物料名称</Grid.Item>
        <Grid.Item>{record.itemName}</Grid.Item>
        <Grid.Item>数量/单位</Grid.Item>
        <Grid.Item>{`${record.qty} ${record.itemUnit}/${record.pkgUnit}`}</Grid.Item>
      </Grid>
    </Card>
  );

  useEffect(() => {
    if ("cordova" in window) {
      if (UnpackOpsObj.subscribe) {
        unSubscribeScanEvent(UnpackOpsObj.handleScan);
        document.removeEventListener("resume", UnpackOpsObj.subscribe);
        document.removeEventListener("pause", UnpackOpsObj.unsubscribe);
      }

      UnpackOpsObj.setFields = ({ barcode, parseResult }) => {
        let { items } = parseResult;
        form.setFields([{ name: "palletBarcode", value: barcode }]);
        setItems(items);
      };

      UnpackOpsObj.handleScan = (e) => {
        callNativeApi({
          classFullName: BARCODE_PARSER,
          action: "parse",
          params: { barcode: e.scannerdata, bizType: "UNPACK" },
          needNonce: false,
        })
          .then((resp) => {
            let result = resp.data ? resp.data.payload : resp.payload;
            if (result.ruleType === "PALLET") {
              // 托码
              UnpackOpsObj.setFields({
                barcode: e.scannerdata,
                parseResult: result,
              });
            }
            dispatch(createAction(SET_SCAN_DATA, null));
            return;
          })
          .catch((error) => console.log(error));
      };
      UnpackOpsObj.subscribe = () =>
        subscribeScanEvent(UnpackOpsObj.handleScan);
      UnpackOpsObj.unsubscribe = () =>
        unSubscribeScanEvent(UnpackOpsObj.handleScan);

      subscribeScanEvent(UnpackOpsObj.handleScan);
      document.addEventListener("resume", UnpackOpsObj.subscribe);
      document.addEventListener("pause", UnpackOpsObj.unsubscribe);

      return () => {
        unSubscribeScanEvent(UnpackOpsObj.handleScan);
        document.removeEventListener("resume", UnpackOpsObj.subscribe);
        document.removeEventListener("pause", UnpackOpsObj.unsubscribe);
        UnpackOpsObj.subscribe = null;
        UnpackOpsObj.unsubscribe = null;
        UnpackOpsObj.setFields = null;
        UnpackOpsObj.handleScan = null;
      };
    }
  }, []);

  const handleSave = () => {
    dispatch(
      createAction(SAGA_UNPACK_SAVE, {
        palletBarcode: form.getFieldValue("palletBarcode"),
        callback: () => {
          Toast.show({
            icon: "success",
            content: "保存成功",
            maskClickable: false,
          });
          setItems([]);
          form.resetFields();
        },
      })
    );
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item name="palletBarcode" label="托码" rules={REQUIRED_RULE}>
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          {items.length === 0 ? <Form.Header>物料信息</Form.Header> : null}
          {items.length === 0 ? (
            <ErrorBlock status="empty" title="暂无数据" description="" />
          ) : null}
        </Form>
        {items.length > 0 ? (
          <List header="物料信息">
            {items.map((i, idx) => (
              <List.Item
                key={idx}
                style={{ backgroundColor: "#F5F5F5" }}
                description={
                  <Description
                    title={`${idx + 1}/${items.length}`}
                    record={i}
                  />
                }
              />
            ))}
          </List>
        ) : null}
      </div>
      <BottomBtn
        items={[
          {
            btnTxt: "保存",
            color: "danger",
            disabled: !(items.length > 0),
            handler: handleSave,
          },
        ]}
      />
    </>
  );
};

export default Ops;
